import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { ApiResponse } from '@common/interfaces/api-response.interface'
import { PaginationResult } from '@common/interfaces/pagination-result.interface';
import { Users } from './entities/user.entity'
import { Injectable } from '@nestjs/common';
import { GetUserDto } from './dto/get-user.dto';
import { CreateUserDto } from './dto/create-user.dto';

@Injectable()
export class UsersService {
  constructor(
    @InjectRepository(Users)
    private usersRepository: Repository<Users>,
  ) { }

  async findAll(getUserDto: GetUserDto): Promise<ApiResponse<PaginationResult<Users>>> {
    try {
      const { page, pageSize, username, email } = getUserDto;
      const query = this.usersRepository.createQueryBuilder('users');

      if (username) {
        query.andWhere('users.username LIKE :username', { username: `%${username}%` });
      }

      if (email) {
        query.andWhere('users.email LIKE :email', { email: `%${email}%` });
      }

      const skip = (page - 1) * pageSize;
      const [data, total] = await query
        .skip(skip)
        .take(pageSize)
        .getManyAndCount();

      return {
        code: 200,
        message: '查询成功',
        data: {
          data,
          total,
          page,
          pageSize,
        },
      };
    } catch (error) {
      console.error('Database error:', error);
      return {
        code: 500,
        message: '查询失败',
        error: error.message,
      };
    }
  }

  async create(createUserDto: CreateUserDto): Promise<ApiResponse<Users>> {
    try {
      const user = this.usersRepository.create(createUserDto);
      const savedUser = await this.usersRepository.save(user);

      return {
        code: 201,
        message: '用户创建成功',
        data: savedUser,
      };
    } catch (error) {
      console.error('Database error:', error);
      return {
        code: 500,
        message: '用户创建失败',
        error: error.message,
      };
    }
  }
} 